package com.chookss.tools.bigImage.view

import android.Manifest
import android.app.Activity
import android.app.ActivityOptions
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.os.*
import android.text.TextUtils
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import android.view.animation.DecelerateInterpolator
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.PermissionChecker
import androidx.viewpager.widget.ViewPager.SimpleOnPageChangeListener
import com.bumptech.glide.Glide
import com.bumptech.glide.request.transition.Transition
import com.chookss.R
import com.chookss.Urls
import com.chookss.home.gallery.GalleryDetailActivity
import com.chookss.tools.FileUtilss.getFileSize
import com.chookss.tools.MyEvent
import com.chookss.tools.MyToast
import com.chookss.tools.SignUtils2
import com.chookss.tools.Utils
import com.chookss.tools.bigImage.ImagePreview
import com.chookss.tools.bigImage.bean.ImageInfo
import com.chookss.tools.bigImage.glide.FileTarget
import com.chookss.tools.bigImage.glide.ImageLoader.getGlideCacheFile
import com.chookss.tools.bigImage.glide.progress.OnProgressListener
import com.chookss.tools.bigImage.glide.progress.ProgressManager.addListener
import com.chookss.tools.bigImage.tool.common.HandlerHolder
import com.chookss.tools.bigImage.tool.file.FileUtil
import com.chookss.tools.bigImage.tool.image.ImageUtil
import com.chookss.tools.bigImage.tool.ui.ToastUtil
import com.chookss.tools.okgoconfig.MyHttpRequest
import com.chookss.tools.okgoconfig.callback.ObserverCallback
import com.chookss.tools.okgoconfig.model.LzyResponse
import com.chookss.wxapi.WeChatShareUtil
import com.google.android.material.transition.platform.MaterialContainerTransform
import com.google.android.material.transition.platform.MaterialContainerTransformSharedElementCallback
import com.google.gson.reflect.TypeToken
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONException
import org.json.JSONObject
import java.io.*
import java.util.*

/**
 * @author 工藤
 * @email qinglingou@gmail.com
 */
class ImagePreviewActivity2 : AppCompatActivity(), Handler.Callback, View.OnClickListener {

    private lateinit var context: Activity

    private lateinit var handlerHolder: HandlerHolder
    private lateinit var imageInfoList: MutableList<ImageInfo>
    private var currentItem = 0

    private var isShowCloseButton = false
    private var isShowOriginButton = false
    private var isShowIndicator = false

    private lateinit var imagePreviewAdapter: ImagePreviewAdapter2
    private lateinit var viewPager: HackyViewPager
    private lateinit var tv_indicator: TextView
    private lateinit var topRl: RelativeLayout
    private lateinit var llBack: LinearLayout
    private lateinit var llBottom: LinearLayout
    private lateinit var llShare: LinearLayout
    private lateinit var llDetail: LinearLayout
    private lateinit var llLocation: LinearLayout
    private lateinit var llLocationCity: LinearLayout
    private lateinit var llCollect: LinearLayout
    private lateinit var tvPeopleTime: TextView
    private lateinit var tvLocation: TextView
    private lateinit var tvTitle: TextView
    private lateinit var tvTime: TextView
    private lateinit var ivCollect: ImageView
    private lateinit var fm_center_progress_container: FrameLayout
    private lateinit var rootView: View
    private lateinit var progressParentLayout: View

    private var isUserCustomProgressView = false

    // 指示器显示状态
    private var indicatorStatus = false
    private var isCollect = false

    // 下载按钮显示状态
    private var downloadButtonStatus = false

    // 是否全屏
     var isFullScreen = false

    // 关闭按钮显示状态
    private var currentItemOriginPathUrl: String? = ""
    private var imageCode: String? = ""
    private var lastProgress = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        // 只有安卓版本大于 5.0 才可使用过度动画
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && !TextUtils.isEmpty(ImagePreview.instance.transitionShareElementName)) {
            window.requestFeature(Window.FEATURE_ACTIVITY_TRANSITIONS)
            findViewById<View>(android.R.id.content).transitionName = "shared_element_container"
            setEnterSharedElementCallback(MaterialContainerTransformSharedElementCallback())
            window.sharedElementEnterTransition =
                MaterialContainerTransform().addTarget(android.R.id.content).setDuration(300L)
            window.sharedElementReturnTransition =
                MaterialContainerTransform().addTarget(android.R.id.content).setDuration(250L)
        }
        super.onCreate(savedInstanceState)

        // R.layout.sh_layout_preview
        setContentView(R.layout.sh_layout_preview2)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val window = window
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            window.decorView.systemUiVisibility =
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            window.statusBarColor = Color.TRANSPARENT
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        }
        context = this
        handlerHolder = HandlerHolder(this)
        imageInfoList = ImagePreview.instance.getImageInfoList()
        if (imageInfoList.isEmpty()) {
            onBackPressed()
            return
        }
        currentItem = ImagePreview.instance.index
        isShowCloseButton = ImagePreview.instance.isShowCloseButton
        isShowIndicator = ImagePreview.instance.isShowIndicator
        currentItemOriginPathUrl = imageInfoList[currentItem].originUrl
        isShowOriginButton = ImagePreview.instance.isShowOriginButton(currentItem)
        if (isShowOriginButton) {
            // 检查缓存是否存在
            checkCache(currentItemOriginPathUrl)
        }
        rootView = findViewById(R.id.rootView)
        viewPager = findViewById(R.id.viewPager)
        tv_indicator = findViewById(R.id.tv_indicator)
        topRl = findViewById(R.id.topRl)
        llBack = findViewById(R.id.llBack)
        llBottom = findViewById(R.id.llBottom)
        llShare = findViewById(R.id.llShare)
        llDetail = findViewById(R.id.llDetail)
        llLocation = findViewById(R.id.llLocation)
        llLocationCity = findViewById(R.id.llLocationCity)
        tvPeopleTime = findViewById(R.id.tvPeopleTime)
        tvLocation = findViewById(R.id.tvLocation)
        tvTitle = findViewById(R.id.tvTitle)
        llCollect = findViewById(R.id.llCollect)
        tvTime = findViewById(R.id.tvTime)
        ivCollect = findViewById(R.id.ivCollect)
        val statusBarHeight = Utils.getStatusBarHeight(this)
        val photoViewParams = topRl.getLayoutParams() as RelativeLayout.LayoutParams
        photoViewParams.setMargins(0, statusBarHeight, 0, 0)
        topRl.setLayoutParams(photoViewParams)
        fm_center_progress_container = findViewById(R.id.fm_center_progress_container)
        fm_center_progress_container.visibility = View.GONE
        val progressLayoutId = ImagePreview.instance.progressLayoutId
        // != -1 即用户自定义了view
        if (progressLayoutId != -1) {
            // add用户自定义的view到frameLayout中，回调进度和view
            progressParentLayout = View.inflate(
                context,
                ImagePreview.instance.progressLayoutId,
                null
            )
            isUserCustomProgressView = run {
                fm_center_progress_container.removeAllViews()
                fm_center_progress_container.addView(progressParentLayout)
                true
            }
        } else {
            // 使用默认的textView进行百分比的显示
            isUserCustomProgressView = false
        }
        // 返回按钮
        llBack.setOnClickListener(this)
        // 分享按钮
        llShare.setOnClickListener(this)
        // 详情按钮
        llDetail.setOnClickListener(this)
        llCollect.setOnClickListener(this)
        indicatorStatus = if (!isShowIndicator) {
            tv_indicator.visibility = View.GONE
            false
        } else {
            if (imageInfoList.size > 1) {
                tv_indicator.visibility = View.VISIBLE
                true
            } else {
                tv_indicator.visibility = View.GONE
                false
            }
        }
        // 设置顶部指示器背景shape
        if (ImagePreview.instance.indicatorShapeResId > 0) {
            tv_indicator.setBackgroundResource(ImagePreview.instance.indicatorShapeResId)
        }
        // 更新进度指示器
        tv_indicator.text = String.format(
            getString(R.string.indicator),
            (currentItem + 1).toString(),
            (imageInfoList.size).toString()
        )
        imagePreviewAdapter = ImagePreviewAdapter2(this, imageInfoList)
        viewPager.adapter = imagePreviewAdapter
        viewPager.currentItem = currentItem
        setData()
        viewPager.setOnClickListener(View.OnClickListener {
            if (isFullScreen) {
                isFullScreen = false
                setAnim(1)
            } else {
                isFullScreen = true
                setAnim(0)
            }
        })
        viewPager.addOnPageChangeListener(object : SimpleOnPageChangeListener() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                ImagePreview.instance.bigImagePageChangeListener?.onPageSelected(position)
                currentItem = position
                currentItemOriginPathUrl = imageInfoList[position].originUrl
                isShowOriginButton = ImagePreview.instance.isShowOriginButton(currentItem)
                if (isShowOriginButton) {
                    // 检查缓存是否存在
                    checkCache(currentItemOriginPathUrl)
                } else {
                    gone()
                }
                // 更新进度指示器
                tv_indicator.text = String.format(
                    getString(R.string.indicator),
                    (currentItem + 1).toString(),
                    (imageInfoList.size).toString()
                )
                // 如果是自定义百分比进度view，每次切换都先隐藏，并重置百分比
                if (isUserCustomProgressView) {
                    fm_center_progress_container.visibility = View.GONE
                    lastProgress = 0
                }
                setData()
            }

            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels)
                ImagePreview.instance.bigImagePageChangeListener?.onPageScrolled(
                    position,
                    positionOffset,
                    positionOffsetPixels
                )
            }

            override fun onPageScrollStateChanged(state: Int) {
                super.onPageScrollStateChanged(state)
                ImagePreview.instance.bigImagePageChangeListener?.onPageScrollStateChanged(state)
            }
        })
        // 绑定
        EventBus.getDefault().register(this)
    }

    private fun setData() {
    //初始化当前页数据
        if (!Utils.isNull(imageInfoList[currentItem].day)){
            tvTitle.text = imageInfoList[currentItem].day
            tvTime.text =imageInfoList[currentItem].minutes
            tvPeopleTime.text = imageInfoList[currentItem].name+" "+imageInfoList[currentItem].date
        }else{
            tvTitle.text = ""
            tvTime.text = ""
            tvPeopleTime.text = imageInfoList[currentItem].name
        }
        setLocData()
    }
    private fun setLocData() {
        //初始化水印数据
        if (Utils.isNull(imageInfoList[currentItem].groupCode)){
            imageCode= imageInfoList[currentItem].imageCode
            imageInfoList[currentItem].imageCode?.let { addImagePalyCount(it,currentItem) }
        }else{
            if (imageInfoList[currentItem].groupCode.equals("1")){
                llLocation.visibility=View.VISIBLE
                if (Utils.isNull(imageInfoList[currentItem].groupCode)){
                    if (!Utils.isNull(imageInfoList[currentItem].location?.trim())){
                        if(imageInfoList[currentItem].location?.trim().equals("a")){
                            tvLocation.text="未知"
                        }else{
                            tvLocation.text=imageInfoList[currentItem].location
                        }
                        llLocationCity.visibility=View.VISIBLE
                    }else{
                        tvLocation.text="未知"
                        llLocationCity.visibility=View.VISIBLE
                    }
                }
            }else{
                llLocation.visibility=View.GONE
            }
        }
    }
    /**
     * 下载当前图片到SD卡
     */
    private fun downloadCurrentImg() {
        downloadPicture(context.applicationContext, currentItemOriginPathUrl)
    }

    fun downloadPicture(context: Context, url: String?) {
        Glide.with(context).downloadOnly().load(url).into(object : FileTarget() {
            override fun onLoadStarted(placeholder: Drawable?) {
                super.onLoadStarted(placeholder)
//                ToastUtil.instance.showShort(
//                    context,
//                    context.getString(R.string.toast_start_download)
//                )
                super.onLoadStarted(placeholder)
            }

            override fun onLoadFailed(errorDrawable: Drawable?) {
                super.onLoadFailed(errorDrawable)
                ToastUtil.instance.showShort(context, context.getString(R.string.toast_save_failed))
            }

            override fun onResourceReady(resource: File, transition: Transition<in File>?) {
                super.onResourceReady(resource, transition)
                // 传入的保存文件夹名
                val downloadFolderName = ImagePreview.instance.folderName
                // 保存的图片名称
                var name = System.currentTimeMillis().toString() + ""
                val mimeType = ImageUtil.getImageTypeWithMime(resource.absolutePath)
                name = "$name.$mimeType"
                val path = getExternalFilesDir(Urls.IMAGEFOLDER)?.absolutePath + "/"
                FileUtil.createFileByDeleteOldFile(path + name)
                val result = FileUtil.copyFile(resource, path, name)
                if (result) {
                    imageInfoList[currentItem].imageCode?.let { shareImage(it) }
                    WeChatShareUtil.getInstance(context).imageShare(path + name, mimeType,getFileSize(resource))
                    onBackPressed()
                } else {
                    ToastUtil.instance.showShort(
                        context,
                        context.getString(R.string.toast_save_failed)
                    )
                }
            }
        })
    }

    private fun convertPercentToBlackAlphaColor(percent: Float): Int {
        var percent = percent
        percent = Math.min(1f, Math.max(0f, percent))
        val intAlpha = (percent * 255).toInt()
        val stringAlpha = Integer.toHexString(intAlpha).toLowerCase(Locale.ROOT)
        val color = "#" + (if (stringAlpha.length < 2) "0" else "") + stringAlpha + "000000"
        return Color.parseColor(color)
    }

    fun setAlpha(alpha: Float) {
        val colorId = convertPercentToBlackAlphaColor(alpha)
        rootView.setBackgroundColor(colorId)
        if (alpha >= 1) {
            if (indicatorStatus) {
                tv_indicator.visibility = View.VISIBLE
            }
        } else {
            tv_indicator.visibility = View.GONE
        }
    }

    private fun getRealIndexWithPath(path: String?): Int {
        for (i in imageInfoList.indices) {
            if (path.equals(imageInfoList[i].originUrl, ignoreCase = true)) {
                return i
            }
        }
        return 0
    }

    private fun checkCache(url: String?): Boolean {
        val cacheFile = getGlideCacheFile(context, url)
        return if (cacheFile != null && cacheFile.exists()) {
            gone()
            true
        } else {
            visible()
            false
        }
    }

    override fun onClick(v: View) {
        val i = v.id
        if (i == R.id.llShare) {
            val downloadClickListener = ImagePreview.instance.downloadClickListener
            if (downloadClickListener != null) {
                val interceptDownload = downloadClickListener.isInterceptDownload
                if (interceptDownload) {
                    // 拦截了下载，不执行下载
                } else {
                    // 没有拦截下载
                    checkAndDownload()
                }
                ImagePreview.instance.downloadClickListener?.onClick(context, v, currentItem)
            } else {
                checkAndDownload()
            }
        } else if (i == R.id.btn_show_origin) {
            handlerHolder.sendEmptyMessage(0)
        } else if (i == R.id.llBack) {
            onBackPressed()
        } else if (i == R.id.llDetail) {
            val intent = Intent(this, GalleryDetailActivity::class.java)
            intent.putExtra("imageCode", imageInfoList[currentItem].imageCode)
            startActivity(intent)
            onBackPressed()
        }else if (i == R.id.llCollect) {
            if (isCollect) {
                imageInfoList[currentItem].imageCode?.let { collectPic(it, "0") }
                isCollect = false
                ivCollect.setBackgroundResource(R.drawable.icon_shoucang)
            } else {
                imageInfoList[currentItem].imageCode?.let { collectPic(it, "1") }
                isCollect = true
                ivCollect.setBackgroundResource(R.drawable.icon_quxiaoshoucang)
            }
        }
    }

    private fun checkAndDownload() {
        // 检查权限
        if (ContextCompat.checkSelfPermission(
                context,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(
                    this@ImagePreviewActivity2,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                )
            ) {
                // 拒绝权限
                ToastUtil.instance.showShort(
                    context,
                    getString(R.string.toast_deny_permission_save_failed)
                )
            } else {
                //申请权限
                ActivityCompat.requestPermissions(
                    this@ImagePreviewActivity2,
                    arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                    1
                )
            }
        } else {
            // 下载当前图片
            downloadCurrentImg()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int, permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 1) {
            for (i in permissions.indices) {
                if (grantResults[i] == PermissionChecker.PERMISSION_GRANTED) {
                    downloadCurrentImg()
                } else {
                    ToastUtil.instance.showShort(
                        context,
                        getString(R.string.toast_deny_permission_save_failed)
                    )
                }
            }
        }
    }

    private fun gone() {
        handlerHolder.sendEmptyMessage(3)
    }

    private fun visible() {
        handlerHolder.sendEmptyMessage(4)
    }

    private fun loadOriginImage(path: String?) {
        Glide.with(context).downloadOnly().load(path).into(object : FileTarget() {
        })
        addListener(path, object : OnProgressListener {
            override fun onProgress(
                url: String?,
                isComplete: Boolean,
                percentage: Int,
                bytesRead: Long,
                totalBytes: Long
            ) {
                if (isComplete) { // 加载完成
                    val message = handlerHolder.obtainMessage()
                    val bundle = Bundle()
                    bundle.putString("url", url)
                    message.what = 1
                    message.obj = bundle
                    handlerHolder.sendMessage(message)
                } else { // 加载中，为减少回调次数，此处做判断，如果和上次的百分比一致就跳过
                    if (percentage == lastProgress) {
                        return
                    }
                    lastProgress = percentage
                    val message = handlerHolder.obtainMessage()
                    val bundle = Bundle()
                    bundle.putString("url", url)
                    bundle.putInt("progress", percentage)
                    message.what = 2
                    message.obj = bundle
                    handlerHolder.sendMessage(message)
                }
            }
        })
    }
    private fun addImagePalyCount(imageCode: String,index :Int) {
        val map: MutableMap<String, String> = HashMap()
        map["imageCode"] = imageCode
        MyHttpRequest.getDefault().getRequestCompat(
            null,
            Urls.addImagePalyCount,
            SignUtils2.makeSignStr(map),
            false,
            object : ObserverCallback<String?> {
                override fun onError(errorMsg: String) {}
                override fun onSuccess(t: String?) {
                    var reObject: JSONObject? = null
                    try {
                        reObject = JSONObject(t)
                        if ("200".equals(reObject.getString("code"))) {
                           var reObjects: JSONObject?=reObject.getJSONObject("data");
                            if (reObjects?.getString("isCollect").equals("1")) {
                                isCollect = true
                                ivCollect.setBackgroundResource(R.drawable.icon_quxiaoshoucang)
                            } else {
                                isCollect = false
                                ivCollect.setBackgroundResource(R.drawable.icon_shoucang)
                            }
                            if(Utils.isNull(reObjects?.getString("groupCode"))){
                                imageInfoList[currentItem].groupCode="1"
                            }else{
                                imageInfoList[currentItem].groupCode=reObjects?.getString("groupCode")
                            }
                            setLocData()
                        }
                    } catch (e: JSONException) {
                        e.printStackTrace()
                    }

                }
            })
    }
    private fun shareImage(imageCode: String) {
        val map: MutableMap<String, String> = HashMap()
        map["imageCodes"] = imageCode
        MyHttpRequest.getDefault().postRequestCompat(
            null,
            Urls.shareImage,
            SignUtils2.makeSignStr(map),
            false,
            object : ObserverCallback<String?> {
                override fun onError(errorMsg: String) {}
                override fun onSuccess(t: String?) {
                    var reObject: JSONObject? = null
                }
            })
    }
    private fun collectPic(imageCode: String, type: String) {
        val map: MutableMap<String, String> = HashMap()
        map["collectId"] = imageCode
        map["collectStatus"] = type
        map["collectType"] = "4"
        MyHttpRequest.getDefault().postRequest(object : TypeToken<LzyResponse<String?>?>() {}.type,
            null,
            Urls.toCollect,
            SignUtils2.makeSignStr(map),
            false,
            object : ObserverCallback<String?> {

                override fun onError(errorMsg: String) {
                    MyToast.show(Utils.onErrorTips(errorMsg))
                }

                override fun onSuccess(t: String?) {
                    if (type == "0") {
                        MyToast.show("取消收藏")
                    } else {
                        MyToast.show("收藏成功")
                    }
                    EventBus.getDefault().post(MyEvent("picRefresh"))
                }
            })
    }
    companion object {
        fun activityStart(context: Context?) {
            if (context == null) {
                return
            }
            val intent = Intent()
            intent.setClass(context, ImagePreviewActivity2::class.java)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                // 过度动画效果只对安卓 5.0 以上有效
                val transitionView = ImagePreview.instance.transitionView
                val transitionShareElementName = ImagePreview.instance.transitionShareElementName
                // 如果未设置则使用默认动画
                if (transitionView != null && transitionShareElementName != null) {
                    val options = ActivityOptions.makeSceneTransitionAnimation(
                        context as Activity?,
                        transitionView,
                        transitionShareElementName
                    )
                    context.startActivity(intent, options.toBundle())
                } else {
                    context.startActivity(intent)
                    if (context is Activity) {
                        context.overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
                    }
                }
            } else {
                // 低于 5.0 使用默认动画
                context.startActivity(intent)
                if (context is Activity) {
                    context.overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
                }
            }
        }
    }

    override fun handleMessage(msg: Message): Boolean {
        if (msg.what == 0) {
            // 点击查看原图按钮，开始加载原图
            val path = imageInfoList[currentItem].originUrl
            visible()
            if (isUserCustomProgressView) {
                gone()
            } else {
//                btn_show_origin.text = "0 %"
            }
            if (checkCache(path)) {
                val message = handlerHolder.obtainMessage()
                val bundle = Bundle()
                bundle.putString("url", path)
                message.what = 1
                message.obj = bundle
                handlerHolder.sendMessage(message)
                return true
            }
            loadOriginImage(path)
        } else if (msg.what == 1) {
            // 加载完成
            val bundle = msg.obj as Bundle
            val url = bundle.getString("url")
            gone()
            if (currentItem == getRealIndexWithPath(url)) {
                if (isUserCustomProgressView) {
                    fm_center_progress_container.visibility = View.GONE
                    progressParentLayout.visibility = View.GONE
                    ImagePreview.instance.onOriginProgressListener?.finish(progressParentLayout)
                    imagePreviewAdapter.loadOrigin(imageInfoList[currentItem])
                } else {
                    imagePreviewAdapter.loadOrigin(imageInfoList[currentItem])
                }
            }
        } else if (msg.what == 2) {
            // 加载中
            val bundle = msg.obj as Bundle
            val url = bundle.getString("url")
            val progress = bundle.getInt("progress")
            if (currentItem == getRealIndexWithPath(url)) {
                if (isUserCustomProgressView) {
                    gone()
                    fm_center_progress_container.visibility = View.VISIBLE
                    progressParentLayout.visibility = View.VISIBLE
                    ImagePreview.instance.onOriginProgressListener?.progress(
                        progressParentLayout,
                        progress
                    )
                } else {
                    visible()
//                    btn_show_origin.text = String.format("%s %%", progress)
                }
            }
        } else if (msg.what == 3) {
            // 隐藏查看原图按钮
//            btn_show_origin.setText(R.string.btn_original)
//            fm_image_show_origin_container.visibility = View.GONE
//            originalStatus = false
        } else if (msg.what == 4) {
            // 显示查看原图按钮
//            fm_image_show_origin_container.visibility = View.VISIBLE
//            originalStatus = true
        }
        return true
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMoonEvent(messageEvent: MyEvent) {
        //事件订阅者处理事件
        if (messageEvent.hashMap != null) {
            val map = messageEvent.hashMap
            if(map.containsKey("ImagePreviewAdapter2_position")){
                if (isFullScreen) {
                    isFullScreen = false
                    setAnim(1)
                } else {
                    isFullScreen = true
                    setAnim(0)
                }
            }
        } else {
            val msg = messageEvent.message
        }
    }

    override fun onBackPressed() {
        if (isFullScreen) {
            isFullScreen = false
            setAnim(1)
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                supportFinishAfterTransition()
            } else {
                finish()
            }
        }

    }

    override fun finish() {
        super.finish()
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
        ImagePreview.instance.reset()
        imagePreviewAdapter.closePage()
    }

    fun setAnim(type: Int) {
        //1展开  0缩回只留大图  全屏
        if (type == 0) {
            fadeOut(topRl, 300, null, true)
            fadeOut(llLocation, 300, null, true)
            fadeOut(llBottom, 300, null, true)
        } else {
            fadeIn(topRl, 300, null, true)
            fadeIn(llLocation, 300, null, true)
            fadeIn(llBottom, 300, null, true)
        }
    }

    fun fadeOut(
        view: View?,
        duration: Int,
        listener: Animation.AnimationListener?,
        isNeedAnimation: Boolean
    ): AlphaAnimation? {
        if (view == null) {
            return null
        }
        return if (isNeedAnimation) {
            val alpha = AlphaAnimation(1f, 0f)
            alpha.interpolator = DecelerateInterpolator()
            alpha.duration = duration.toLong()
            alpha.setAnimationListener(object : Animation.AnimationListener {
                override fun onAnimationStart(animation: Animation) {
                    listener?.onAnimationStart(animation)
                }

                override fun onAnimationEnd(animation: Animation) {
                    view.visibility = View.GONE
                    listener?.onAnimationEnd(animation)
                }

                override fun onAnimationRepeat(animation: Animation) {
                    listener?.onAnimationRepeat(animation)
                }
            })
            view.startAnimation(alpha)
            alpha
        } else {
            view.visibility = View.GONE
            null
        }
    }

    fun fadeIn(
        view: View?,
        duration: Int,
        listener: Animation.AnimationListener?,
        isNeedAnimation: Boolean
    ): AlphaAnimation? {
        if (view == null) {
            return null
        }
        return if (isNeedAnimation) {
            view.visibility = View.VISIBLE
            val alpha = AlphaAnimation(0f, 1f)
            alpha.interpolator = DecelerateInterpolator()
            alpha.duration = duration.toLong()
            alpha.fillAfter = true
            if (listener != null) {
                alpha.setAnimationListener(listener)
            }
            view.startAnimation(alpha)
            alpha
        } else {
            view.alpha = 1f
            view.visibility = View.VISIBLE
            null
        }
    }
    override fun onDestroy() { /*兼容14之前的版本需要在基类中添加以下代码*/
        EventBus.getDefault().unregister(this);
        super.onDestroy()
    }
}